package com.fjnu.dao;

import com.fjnu.entity.Tag;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jdbc.core.BeanPropertyRowMapper;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.stereotype.Repository;

import java.util.List;

@Repository
public class TagDao {

    @Autowired
    private JdbcTemplate jdbcTemplate;

    /**
     * 查询所有标签
     */
    public List<Tag> selectAll() {
        String sql = "SELECT id, tag_name, create_time FROM tag ORDER BY create_time DESC";
        return jdbcTemplate.query(sql, new BeanPropertyRowMapper<>(Tag.class));
    }

    /**
     * 删除标签
     */
    public int delete(Integer tagId) {
        if (tagId == null) {
            return 0;
        }
        // 先删除关联关系
        String deleteRelationSql = "DELETE FROM article_tag WHERE tag_id = ?";
        jdbcTemplate.update(deleteRelationSql, tagId);
        
        // 再删除标签本身
        String deleteSql = "DELETE FROM tag WHERE id = ?";
        return jdbcTemplate.update(deleteSql, tagId);
    }

    /**
     * 新增标签
     * 规则：无显式参数校验，但需确保标签名非空（业务隐含要求），成功返回 1，失败返回 0
     */
    public int insert(Tag tag) {
        if (tag.getTagName() == null) {
            return 0;
        }
        String sql = "INSERT INTO tag(tag_name, create_time) VALUES(?, NOW())";
        return jdbcTemplate.update(sql, tag.getTagName());
    }

    /**
     * 新增文章标签（建立文章与标签的多对多关联）
     * 规则：需确保 articleId 和 tagId 非空，成功返回 1，失败返回 0
     */
    public int insertArticleTag(Integer articleId, Integer tagId) {
        if (articleId == null || tagId == null) {
            return 0;
        }
        String sql = "INSERT INTO article_tag(article_id, tag_id) VALUES(?, ?)";
        return jdbcTemplate.update(sql, articleId, tagId);
    }
}